package com.pansoft.openplanet.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.BuyTCActivity;
import com.pansoft.openplanet.activity.SellTCActivity;
import com.pansoft.openplanet.bean.TradeBean;
import com.pansoft.openplanet.util.TCMathUtil;
import com.pansoft.openplanet.widget.TCValueBar;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 交易 页面
 *
 * @author YQS
 */

public class TransactionFragment extends BaseFragment implements View.OnClickListener {
    private EditText etWeiTuoPrice;
    private EditText etTransactionCount;
    private EditText etTransactionPrice;
    private LinearLayout llTioami;
    private LinearLayout llDimi;
    private RecyclerView sellRecyclew;
    private RecyclerView buyRecyclew;
    private List<TradeBean> sellListData;
    private List<TradeBean> buyListData;
    private BuyAdapter buyAdapter;
    private SellAdapter sellAdapter;
    private View rootView;
    private boolean isWeiTuoFocus = false;
    private boolean isTransCountFocus = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        initView(inflater);
        initData();
        return rootView;
    }

    private void initView(LayoutInflater inflater) {
        rootView = inflater.inflate(R.layout.talk_chain_fragment_transaction, null);

        etWeiTuoPrice = rootView.findViewById(R.id.et_weiTuoPrice);
        etTransactionCount = rootView.findViewById(R.id.et_transactionCount);
        etTransactionPrice = rootView.findViewById(R.id.et_transactionPrice);
        llTioami = rootView.findViewById(R.id.ll_tioami);
        llDimi = rootView.findViewById(R.id.ll_dimi);
        sellRecyclew = rootView.findViewById(R.id.sellRecyclew);
        buyRecyclew = rootView.findViewById(R.id.buyRecyclew);

//        sellRecyclew.setLayoutManager(new FullyLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, true));
        sellRecyclew.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, true));

        buyRecyclew.setLayoutManager(new LinearLayoutManager(getActivity()));
        llTioami.setOnClickListener(this);
        llDimi.setOnClickListener(this);
        etWeiTuoPrice.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isWeiTuoFocus = true;
                    isTransCountFocus = false;
                } else {
                    isWeiTuoFocus = false;
                }
            }
        });
        etTransactionCount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    isTransCountFocus = true;
                    isWeiTuoFocus = false;
                } else {
                    isTransCountFocus = false;
                }
            }
        });
        etWeiTuoPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setTransPrice(s.toString());
            }
        });
        etTransactionCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!"".equals(etWeiTuoPrice.getText().toString())) {
                    setTransPrice(etWeiTuoPrice.getText().toString());
                }
            }
        });

    }

    private void initData() {
        buyListData = new ArrayList<>();
        sellListData = new ArrayList<>();

        buyAdapter = new BuyAdapter(getActivity(), R.layout.talk_chain_item_trade_trend, buyListData);
        sellAdapter = new SellAdapter(getActivity(), R.layout.talk_chain_item_trade_trend, sellListData);
        buyRecyclew.setAdapter(buyAdapter);
        sellRecyclew.setAdapter(sellAdapter);

        loadData();
    }

    private void loadData() {
        buyListData.clear();
        sellListData.clear();
        for (int i = 0; i < 5; i++) {
            TradeBean bean = new TradeBean.Builder().avatar("").count(String.valueOf(i + 0.21)).percent(5 + i * 8)
                    .title(ResStringUtil.getString(R.string.open_planet_asset_transaction_sale) + (i + 1)).userName(ResStringUtil.getString(R.string.open_planet_asset_transaction_user)  + i).price("2503.97").build();
            sellListData.add(bean);

        }
        for (int i = 0; i < 5; i++) {
            TradeBean bean = new TradeBean.Builder().avatar("").count(String.valueOf(i + 0.21)).percent(20 + i * 5)
                    .title(ResStringUtil.getString(R.string.open_planet_asset_transaction_buy)  + (i + 1)).userName(ResStringUtil.getString(R.string.open_planet_asset_transaction_user)  + i).price("2600.23").build();
            buyListData.add(bean);

        }

        buyAdapter.notifyDataSetChanged();
        sellAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_tioami) {
//            Intent intent = new Intent(getActivity(), TransferActivity.class);
//            intent.putExtra("myaddress", "");
//            intent.putExtra("balance", "0");
//            intent.putExtra("filePath", "");
//            startActivity(intent);
        }
    }

    private void setTransPrice(String weituoPrice) {
        try {
            if ("".equals(weituoPrice) || weituoPrice.startsWith(".")) {
                etTransactionPrice.setText("");
                return;
            }
            String count = etTransactionCount.getText().toString();
            if (!"".equals(count) && !weituoPrice.startsWith(".")) {
                double jiaoyiprice = TCMathUtil.mul(Double.valueOf(weituoPrice), Double.valueOf(count));
                //            etTransactionPrice.setText(TCMathUtil.bigFormat(jiaoyiprice,2)+"");

                String text = new DecimalFormat("0.00").format(TCMathUtil.bigFormat(jiaoyiprice, 2));
                etTransactionPrice.setText(text);
            } else {
                etTransactionPrice.setText("");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class SellAdapter extends CommonAdapter<TradeBean> {
        public SellAdapter(Context context, int layoutId, List<TradeBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final TradeBean bean, int position) {

            TCValueBar tc_value_bar = holder.getView(R.id.tc_value_bar);
            tc_value_bar.setColor(R.color.tc_trade_green);
            TextView tvTradeNo = holder.getView(R.id.tv_trade_no);
            TextView tvTradeUserName = holder.getView(R.id.tv_trade_user_name);
            TextView tvTradePrice = holder.getView(R.id.tv_trade_price);
            TextView tvTradeAmount = holder.getView(R.id.tv_trade_amount);
            ImageView ivAvatar = holder.getView(R.id.iv_avatar);
            tvTradeUserName.setText(bean.getUserName());
            tvTradeNo.setText(bean.getTitle());
            tvTradePrice.setText(bean.getPrice());
            // tc_value_bar.setValue(bean.getPercent());
            tvTradeAmount.setText(bean.getCount());
            tvTradeNo.setTextColor(getResources().getColor(R.color.tc_trade_green_text));
            tc_value_bar.animate(0, bean.getPercent(), 250);
            showAvatar(ivAvatar, bean.getAvatar());
            tvTradeUserName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), BuyTCActivity.class);
                    startActivity(intent);
                }
            });
            tvTradePrice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    etWeiTuoPrice.setText(bean.getPrice());

                    setTransPrice(bean.getPrice());
                }
            });

        }
    }


    private class BuyAdapter extends CommonAdapter<TradeBean> {
        public BuyAdapter(Context context, int layoutId, List<TradeBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final TradeBean bean, int position) {
            TCValueBar tc_value_bar = holder.getView(R.id.tc_value_bar);
            tc_value_bar.setColor(R.color.tc_trade_red1);
            TextView tvTradeNo = holder.getView(R.id.tv_trade_no);
            TextView tvTradeUserName = holder.getView(R.id.tv_trade_user_name);
            TextView tvTradePrice = holder.getView(R.id.tv_trade_price);
            TextView tvTradeAmount = holder.getView(R.id.tv_trade_amount);
            ImageView ivAvatar = holder.getView(R.id.iv_avatar);

            tvTradeUserName.setText(bean.getUserName());
            tvTradeNo.setText(bean.getTitle());
            tvTradePrice.setText(bean.getPrice());
            //tc_value_bar.setValue(bean.getPercent());
            tvTradeAmount.setText(bean.getCount());
            tvTradeNo.setTextColor(getResources().getColor(R.color.tc_trade_red_text));
            tc_value_bar.animate(0, bean.getPercent(), 250);
            showAvatar(ivAvatar, bean.getAvatar());
            tvTradeUserName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), SellTCActivity.class);
                    startActivity(intent);
                }
            });
            tvTradePrice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    etWeiTuoPrice.setText(bean.getPrice());

                    setTransPrice(bean.getPrice());
                }
            });
        }
    }

    /**
     * 显示用户头像
     */
    private void showAvatar(ImageView ivAvatar, String url) {
        RequestOptions options = new RequestOptions()
                .circleCrop().error(R.drawable.contact_default_avatar).placeholder(R.drawable.contact_default_avatar)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(this)
                .load(url)
                .apply(options)
                .into(ivAvatar);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        RefWatcher refWatcher = TalcChainApplication.getRefWatcher(getActivity());
//        refWatcher.watch(this);
    }
}
